<!--这是设置讲师组件-->
<template>
	<div v-loading="btnLoading">
		<div class="addBox">
			<div style="padding: 20px 50px;">
				<div>
          <code v-if="tableLen==0">
            <svg-icon icon-class="message" style="margin-right:10px;color:red;font-size:20px;"></svg-icon>
            备注：暂无讲师，快选择讲师吧
          </code>
          <!-- <el-form  label-width="400px" label-position="right">
            <el-form-item label="选择讲师：" >
              <el-select
                v-model="userId"
                :multiple="false"
                :filterable="true"
                :remote="true"
                :default-first-option="true"
                reserve-keyword
                placeholder="请输入关键词(回车搜索)"
                :remote-method="getUserByKey"
                :loading="loading">
                <el-option
                  v-for="item in teacherInfo"
                  :key="item.userId"
                  :label="item.name"
                  :value="item.name">
                </el-option>
              </el-select>
              <input @keyup.enter="getUserByKey">
            </el-form-item>
          </el-form> -->
          <el-form  label-width="300px" label-position="right">
            <el-form-item label="选择讲师：" >
              <multiselect v-model="value" style='width:420px;margin-right:20px;float:left'
                :options="teacherList"
                track-by="userId"
                label="name"
                placeholder="请输入讲师昵称"
                :loading="isLoading"
                selectLabel="选择"
                deselectLabel="删除"
                @search-change="syncSearchTeachers"
                @remove="removeLecturer"
                @select="teacherOptionSelect"
                :internalSearch="false">
                <span slot='noResult'>无结果</span>
              </multiselect>
            </el-form-item>
          </el-form>
					<table>
						<tr>
							<th>用户名称</th>
							<th>身份</th>
							<th>操作</th>
						</tr>
						<tr v-for="(item,index) in tableData" :key="index">

							<td style="line-height: 32px" v-show="item.status > 0">
								<p style="width: 100%;text-align: left;overflow: hidden;"><span><img :src="item.avatar"/></span><b>{{item.name}}</b></p>
							</td>
							<td v-if="item.role==2" v-show="item.status > 0">讲师</td>
							<td v-else v-show="item.status > 0">管理/讲师</td>
							<td v-show="item.status > 0"><el-button @click="deleteLecturer(item.userId)" type="danger" icon="el-icon-delete" circle></el-button></td>
						</tr>
					</table>
				</div>
				<p v-if="permission == 3" style="text-align: center;line-height: 80px;">
					<el-button @click="saveData" type="primary" icon="el-icon-check" :disabled="btnStatus">保存</el-button>
				</p>
			</div>
		</div>
	</div>
</template>
<script>
import Multiselect from 'vue-multiselect' // 引入 vue-multiselect 组件
import 'vue-multiselect/dist/vue-multiselect.min.css'
import { getUserByKey, getSocialLecturer, saveLecturer } from '@/api/social'
import { interaction_social } from '@/utils/permission'
let timeId
export default {
  components: {
    Multiselect
  },
  data() {
    return {
      permission: 3,
      tableLen: 0,
      tableData: [],
      options: [],
      teacherInfo: [],
      lecturerInfo: [],
      lecturer: [],
      teacherList: [],
      lecturerList: [],
      socialRoomId: null,
      btnLoading: false,
      btnStatus: true,
      isLoading: false,
      userId: '33',
      query: null,
      deleteId: '',
      value: ''
    }
  },
  methods: {
    getModelPermission() {
      this.permission = interaction_social()
    },
    saveData() {
      this.btnLoading = true
      this.btnStatus = false
      console.log('this.tableData: ')
      console.log(this.tableData)
      saveLecturer(this.socialRoomId, { tableData: this.tableData }).then(res => {
        console.log(res.data)
        this.btnLoading = false
        if (res.data.statusCode == 200) {
          this.btnStatus = true
          console.log(res.data)
          this.$message({
            type: 'success',
            message: res.data.data.msg
          })
          this.getLecturer()
          this.value = ''
          this.close()
        } else {
          this.btnStatus = true
          this.$message({
            type: 'error',
            message: res.data.msg
          })
        }
      }).catch(error => {
        this.btnLoading = false
        this.btnStatus = false
        console.log(error)
      })
    },
    deleteLecturer(userId) {
      // console.log(userId)
      this.$message({
        type: 'warning',
        message: '删除后要点击保存才生效'
      })
      this.btnStatus = false
      for (var index in this.tableData) {
        console.log(index)
        if (this.tableData[index].userId == userId) {
          // this.tableData.pop
          if (this.tableData[index].status == 1) { // 已经删除则添加
            this.tableData[index].status = -1
          } else {
            this.tableData.splice(index, 1)
          }
          this.tableLen -= 1
        }
      }
      if (this.tableData.length == 0) {
        this.btnStatus = true
      }
    },
    getLecturer() {
      // console.log(this.$route.params.socialId)
      this.socialRoomId = this.$route.params.socialId
      getSocialLecturer(this.socialRoomId).then(res => {
        this.tableData = res.data.data // 数据库获取的讲师数据给teacherData
        this.lecturerInfo = res.data.data
        console.log('getLecturer: ')
        this.tableLen = res.data.data.length
        this.lecturer = res.data.data
        console.log('hh', this.lecturer)
        // console.log(res.data.data)
      }).catch(err => {
        // console.log('1111')
        console.log(err)
      })
    },
    removeLecturer(removedOption, id) {
      this.btnStatus = false
      console.log('removedOption: ' + removedOption)
      console.log('id: ' + id)
      this.deleteId = removedOption.userId
      for (var index in this.tableData) {
        console.log(index)
        if (this.tableData[index].userId == this.deleteId) {
          // this.tableData.pop
          console.log('removeLecturer: ' + this.tableLen)
          if (this.tableData[index].status == 1) { // 已经删除则添加
            this.tableData[index].status = -1
          } else {
            this.tableData.splice(index, 1)
          }
          this.tableLen -= 1
        }
      }
    },
    hideAddTeacher(msg) {
      this.isShowAddTeacher = msg
    },
    syncSearchTeachers(query) { // 搜索讲师，选择讲师
      clearTimeout(timeId)
      if (query !== '') {
        this.isLoading = true
        console.log('start')
        timeId = setTimeout(() => {
          getUserByKey({ query: query }).then(res => {
            console.log(res.data)
            this.isLoading = false
            const resData = res.data.data
            this.teacherList = []
            for (let i = 0; i < resData.length; i++) {
              this.teacherList.push({
                userId: resData[i].userId,
                avatar: resData[i].avatar,
                mobile: resData[i].mobile,
                status: 2,
                name: resData[i].userName + `（ID: ${resData[i].userId}）`,
                userName: resData[i].userName
              })
            }
          }).catch(err => {
            this.isLoading = false
            console.log(err)
          })
        }, 200)
      } else {
        console.log('end')
        this.isLoading = false
        this.teacherList = []
      }
    },
    teacherOptionSelect(selectedOption, id) {
      // console.log('teacherInfo: ', this.teacherInfo)
      // console.log('sss', selectedOption)
      this.btnStatus = false
      for (var index in this.tableData) {
        console.log(index)
        if (this.tableData[index].userId == selectedOption.userId) {
          if (this.tableData[index].status == -1) { // 已经删除则添加
            this.tableData[index].status = 1
          }
          if (this.tableData[index].status == -2) { // 已经删除就添加
            this.tableData[index].status = 2
          }
          // 存在相等则提前结束该函数
          return
        }
      }
      this.tableData.push(selectedOption)
      this.tableLen += 1
      // console.log('teacherOptionSelect: ' + this.tableLen)
      // this.lecturerInfo.push(tmp)
      // this.lecturer.push(selectedOption)
    },
    close() {
      // 关闭当前窗口
      this.$store.dispatch('delVisitedViews', this.$route).then((views) => {
        const latestView = views.slice(-1)[0]
        console.log(latestView)
        if (latestView) {
          this.$router.push({ path: `/interaction/social` })
        } else {
          this.$router.push('/')
        }
      })
    }
  },
  mounted() {
    this.getModelPermission()
    this.getLecturer()
  }
}
</script>
<style scoped>
	p,h3 {margin:0;padding:0}
	td span{
		width: 30px;
		height: 30px;
		border-radius: 50%;
    overflow: hidden;
    vertical-align: middle;
		display: inline-block;
		margin-right: 10px;
		background: #ccc;
	}
	td span img{
		width: 100%;
		height: 100%;
    vertical-align: middle;
    display: block;
	}
	td b{
		font-weight: 500;
	}
	table {
		border-top: 1px solid #eee;
		width: 60%;
		margin: 0 auto;
		border-collapse:collapse;
	}
	td{
		text-align: center;
	}
	th{
		font-weight: 500;
	}
	tr{
		line-height: 50px;
		border-bottom: 1px solid #eee;
	}
</style>
